import os
import threading
from time import sleep
import random

import numpy as np
from matplotlib import pyplot as plt

import GV
from common.handle import draw_top
from common.util import *
from common.log import GetLog

log = GetLog.get_logger()


class PerformanceThread(threading.Thread):
    def __init__(self, name='none', ThreadId=0):
        threading.Thread.__init__(self)
        self.package = name

        self.PID = int(os.popen('adb shell pidof %s' % self.package).read())

    def run(self) -> None:
        topFileProcess = f"{getOutPutPath()}top_Process_raw_{GV.seed}.txt"
        topFileThread = f"{getOutPutPath()}top_Thread_raw_{GV.seed}.txt"
        meminfoFilePss = f"{getOutPutPath()}meminfo_Pss_raw_{GV.seed}.txt"
        log.info(topFileProcess)
        log.info(topFileThread)
        log.info(meminfoFilePss)
        cmd_process = f"adb shell top -d 1 -n 1 -b | grep -E '{self.package}(\s|$)' >> {topFileProcess}"
        cmd_thread = f"adb shell top -p {self.PID} -n 1 -d 1 -H -b >> {topFileThread}"
        cmd_meminfo = f"adb shell dumpsys meminfo --local {self.package} >> {meminfoFilePss}"
        top_time = []
        cmd_getTime = "adb shell date"
        log.info(f"process:{cmd_process}")
        log.info(f"thread:{cmd_thread}")
        log.info(f"meminfo:{cmd_meminfo}")
        while GV.exit_flag:
            try:
                PID = int(os.popen('adb shell pidof %s' % self.package).read())
                if PID != self.PID:
                    log.error("com.mega.map发生anr")
                    self.PID = PID
                    cmd_thread = f"adb shell top -p {PID} -n 1 -d 1 -H -b >> {topFileThread}"
                os.popen(cmd_process)
                os.popen(cmd_thread)
                os.popen(cmd_meminfo)
                top_time.append(os.popen(cmd_getTime).read().split()[-3])
                log.info("top采集中")
                sleep(1)
            except  Exception as e:
                log.error(e)
        log.info("------------采集完成--------------")
        draw_top([topFileProcess, topFileThread, meminfoFilePss], top_time)


class MonkeyThread(threading.Thread):
    def __init__(self, package, times):
        threading.Thread.__init__(self)
        self.package = package
        self.times = times

    def run(self) -> None:
        monkey_file_path = f" {getOutPutPath()}monkey_{GV.seed}_{getNowTime()}.txt"
        cmd = f'adb shell monkey ' \
              f'--pct-syskeys 0 --pct-anyevent 0 --pct-nav 0 --pct-flip 0 --pct-permission 0 ' \
              f'--pct-appswitch 10 --pct-majornav 0 --pct-trackball 0 ' \
              f'--pct-touch 30 --pct-motion 30 --pct-pinchzoom 30 ' \
              f'--ignore-crashes --ignore-timeouts --ignore-native-crashes --ignore-security-exceptions ' \
              f'-p {self.package}  --throttle 300 -v -v -v  {self.times} -seed {GV.seed} >> {monkey_file_path} '
        log.info(cmd)
        os.system(cmd)


def cpu():
    """
    hreads: 212 total,   0 running, 212 sleeping,   0 stopped,   0 zombie
    Mem:  6711332K total,  6480820K used,   230512K free,  13361152 buffers
    Swap:  3670012K total,   301796K used,  3368216K free,   644592K cached
    800%cpu  81%user   3%nice  65%sys 639%idle   0%iow   6%irq   6%sirq   0%host
     TID USER         PR  NI VIRT  RES  SHR S[%CPU] %MEM     TIME+ THREAD
    8477 system       20   0  19G 542M 192M S  3.2   8.2   0:36.53 AdrenoOsLib
    8434 system       20   0  19G 542M 192M S  3.2   8.2   1:27.42 CarPropTimer
    8416 system       20   0  19G 542M 192M S  3.2   8.2   5:15.36 Tmcom-MapRender

     hreads: 212 total,   0 running, 212 sleeping,   0 stopped,   0 zombie
    Mem:  6711332K total,  6480820K used,   230512K free,  13361152 buffers
    Swap:  3670012K total,   301796K used,  3368216K free,   644592K cached
    800%cpu  81%user   3%nice  65%sys 639%idle   0%iow   6%irq   6%sirq   0%host
     TID USER         PR  NI VIRT  RES  SHR S[%CPU] %MEM     TIME+ THREAD
    8477 system       20   0  19G 542M 192M S  3.2   8.2   0:36.53 AdrenoOsLib
    8434 system       20   0  19G 542M 192M S  3.2   8.2   1:27.42 CarPropTimer
    8416 system       20   0  19G 542M 192M S  3.2   8.2   5:15.36 Tmcom-MapRender
    """

    # cmd = "adb shell top -p 4477 -n 1 -d 1 -H -b >>thread.txt"
    # # os.popen(cmd)
    # n = 50
    # while n:
    #     os.popen(cmd)
    #     sleep(1)
    #     n -= 1

    thread_dict = {}
    with open("thread.txt") as f:
        line = f.readline()
        while line:
            # 去掉特殊字符 \x1b  top 增加-b参数解决空白字符问题

            # line_list = [item for item in line.strip().split() if not item.startswith('\x1b')]
            # if len(line_list) < 2:
            #     line = f.readline()
            #     continue
            line_list = line.strip().split()
            if line_list[-1] == "com.mega.map":
                thread_id = line_list[-2]
                thread_value = float(line_list[-5])
                if thread_id not in thread_dict:
                    thread_dict[thread_id] = []
                else:
                    print(thread_id)
                    thread_value += float(line_list[-5])

            thread_dict[thread_id].append(thread_value)
            line = f.readline()

        print(thread_dict)


def mem_pss(meminfoFile):
    """
 App Summary
                       Pss(KB)                        Rss(KB)
                        ------                         ------
           Java Heap:    77632                          93084
         Native Heap:   370984                         372992
                Code:    45352                         154172
               Stack:     8280                           8292
            Graphics:        0                              0
       Private Other:    47684
              System:    27110
             Unknown:                                   50860

           TOTAL PSS:   577042            TOTAL RSS:   679400       TOTAL SWAP PSS:     9683
"""
    cmd = "adb shell dumpsys meminfo --local com.mega.map >> meminfo.txt"
    N = 10
    while N:
        N -= 1
        os.popen(cmd)
        sleep(1)
    N = 0
    pss_dict = {}
    flag_pss = False
    with open(meminfoFile, 'r') as f:
        line = f.readline()
        while line:
            if " App Summary" in line:
                N += 1
                flag_pss = True
            if "Applications" in line:
                flag_pss = False
            if flag_pss:
                if ":" not in line:
                    line = f.readline()
                    continue
                pss_list = line.strip().split(":")
                key = pss_list[0]
                value = int(pss_list[1].strip().split()[0]) / 1024
                if key == "Unknown":
                    line = f.readline()
                    continue
                if key not in pss_dict:
                    pss_dict[key] = []
                else:
                    pss_dict[key].append(value)

            line = f.readline()
    print(pss_dict)
    x = np.arange(0, N - 1, 1.0)
    fig, ax = plt.subplots(2, 2)

    for key, value in pss_dict.items():
        ax[0][1].plot(x, value, label=key, linewidth=4)
    plt.legend()
    plt.show()
    return pss_dict


def handle_raw_cpu(filename):
    """ 获取cpu使用率 """
    cpu_list = []
    N = 0
    with open(filename, 'r') as f:
        line = f.readline()
        while line:
            if "com.mega.map" in line:
                cpu_list.append(float(line.strip().split()[-4]))
                N += 1
            line = f.readline()
    print(cpu_list)
    print(np.sum(cpu_list) / N)

    pass


if __name__ == '__main__':
    # mem_pss("meminfo.txt")
    # 创建 2x2 子图网格
    handle_raw_cpu(filename="/Users/v_lilinzhi/岚图/mega_cpu_process(1).txt")
    pass
